<template>
  <div class="login">
    <van-nav-bar title="登录" fixed placeholder left-arrow  @click-left="onClickLeft"/>

    <!-- 表单 -->
    <van-form @submit="onChange">
      <van-field v-model="phone" name="手机号" label="手机号"  placeholder="手机号" 
      :rules="[{ pattern,required: true, message: '请填写正确的手机号' }]"/>
      
      <van-field v-model="sms" center name="验证码" clearable label="短信验证码" placeholder="请输入短信验证码"
      :rules="[{ required: true, message: '请填写验证码' }]" >
        <template #button>
          <van-button size="small" type="primary" @click="getCode" native-type="button">发送验证码</van-button>
        </template>
      </van-field>
      <div style="margin: 16px;">
        <van-button round block type="info" native-type="submit">登录</van-button>
      </div>
    </van-form>

    <!-- <span>{{msg}}</span> -->


      
  </div>
</template>

<script>
import { getCodeApi, loginApi } from "@/utils/api";
import { Dialog } from "vant";
export default {
  data() {
    return {
      phone: "",
      sms: "",
      pattern: /^(?:(?:\+|00)86)?1[3-9]\d{9}$/ //正则验证手机号
      // msg: ""
    };
  },

  components: {},

  computed: {},

  mounted() {},

  methods: {
    async onChange() {
      let res = await loginApi({ phone: this.phone, code: this.sms });
      console.log(res);
      if (res.status === "0") {
        localStorage.setItem("token", res.result.token);
        console.log(1);
        Dialog.alert({
          message: res.msg
        }).then(() => {
          this.$router.go(-1);
        });
      } else {
        Dialog.alert({
          message: res.msg
        }).then(() => {});
      }
    },
    getCode() {
      console.log(this.phone);
      getCodeApi({ phone: this.phone, templateId: "537707" }).then(res => {
        if (res.status === "0") {
          console.log(res);
        }
      });
    },
    onClickLeft() {
      this.$router.go(-1);
    }
  }
};
</script>

<style lang="less" scoped>
.login {
  .phone {
    position: relative;
    .van-button--primary {
      position: absolute;
      right: 0;
      top: 0;
      z-index: 1000;
    }
  }
}
</style>
